package com.yct.springcloud.loadBance.impl;

import com.yct.springcloud.loadBance.MyLoadBancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡
 */
@Component("myRotationLoadBancer")
@Slf4j
public class MyRotationLoadBancer implements MyLoadBancer {

    /**
     * 计数器，从 0 开始计数
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance getSingleLoadBancer(List<ServiceInstance> serviceInstances) {
        log.info("轮询负载均衡算法");

        if (serviceInstances != null && serviceInstances.size()>0){
            int idx = atomicInteger.incrementAndGet() % serviceInstances.size();
            return serviceInstances.get(idx);
        }

        return null;
    }
}
